<template>
  <div class="picture-preview">
    <a-image-preview-group>
      <div v-for="(item, index) in props.imgInfoArr" :key="item.id" :title="item.filename || ''">
        <div
          v-if="item.filename.endsWith('.pdf')"
          class="pdf-box"
          @mouseover="handleMouseOver(index)"
          @mouseleave="handleMouseLeave(index)"
          @click="handleImageClick(item)"
        >
          <img class="logo lazyload" :src="uploadPictureCard" />
          <div class="overlay">
            <p v-show="showOverlay[index]" class="preview"><EyeOutlined style="margin-right: 4px" />预览</p>
          </div>
        </div>

        <a-image
          v-else
          class="lazyload"
          :width="104"
          :height="104"
          :alt="item.filename"
          :src="item.fileUrl"
          fallback=""
        />
      </div>
    </a-image-preview-group>
  </div>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { axios } from 'g6-fn'
  import { ref } from 'vue'

  import uploadPictureCard from '@/assets/img/open/common/upload-picture-card.svg'

  import { MaterialVO } from '../../types/index'
  export interface ModalProps {
    imgInfoArr: MaterialVO[]
  }
  const props = withDefaults(defineProps<ModalProps>(), {
    imgInfoArr: () => []
  })

  const showOverlay = ref<boolean[]>([])

  const handleMouseOver = (index: number) => {
    if (props.imgInfoArr[index].filename.endsWith('.pdf')) {
      showOverlay.value[index] = true
    }
  }

  const handleMouseLeave = (index: number) => {
    showOverlay.value[index] = false
  }

  const handleImageClick = async (item: MaterialVO) => {
    if (item.filename.endsWith('.pdf')) {
      try {
        const res = await axios.get(item.fileUrl, { responseType: 'blob' })
        const blob = new Blob([res?.data], { type: 'application/pdf' })
        const href = URL.createObjectURL(blob)
        const open = window.open() as any
        open.location = href
      } catch (error) {
        message.error('预览失败!')
      }
    }
  }
</script>

<style lang="less" scoped>
  .picture-preview {
    display: grid;
    align-items: start;
    width: 100%;
    grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); /* 自动适应列宽 */
    gap: 10px; /* 间距 */
    justify-items: space-between; /* 横向对齐方式 */

    :deep(.ant-image-img) {
      height: 100%;
    }
  }

  .pdf-box {
    position: relative;
    width: 104px;
    height: 104px;

    .overlay {
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      font-size: 14px;

      &:hover {
        cursor: pointer;
        background-color: rgba(0, 0, 0, 0.5);
      }

      .preview {
        overflow: hidden;
        padding: 0 4px;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: white;
      }
    }
  }
</style>
